<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import request, {SERVER_BASE_URL} from "@/utils/request.js"
import { useUserStore } from '@/stores/user'

// 路由和状态管理
const router = useRouter()
const userStore = useUserStore()

// 购物车数据
const cartList = ref([])
// 加载状态
const loading = ref(false)
// 用户ID
const userId = ref(null)

// 检查登录状态
const checkLoginStatus = () => {
  const userInfo = JSON.parse(localStorage.getItem('user'))
  if (!userInfo) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return false
  }
  
  userId.value = userInfo.id
  return true
}

// 计算总价
const totalPrice = computed(() => {
  return cartList.value
    .filter(item => item.selected)
    .reduce((total, item) => {
      return total + item.quantity * item.commodity.price
    }, 0)
})

// 计算选中商品数量
const selectedCount = computed(() => {
  return cartList.value.filter(item => item.selected).length
})

// 是否全选
const isAllSelected = computed(() => {
  return cartList.value.length > 0 && cartList.value.every(item => item.selected)
})

// 获取购物车列表
const getCartList = async () => {
  if (!checkLoginStatus()) return
  
  loading.value = true
  try {
    const res = await request.get('/cart/list', {
      params: { userId: userId.value }
    })
    if (res.code === 200) {
      cartList.value = res.data
    } else {
      ElMessage.error(res.message || '获取购物车失败')
    }
  } catch (error) {
    console.error('获取购物车失败:', error)
    ElMessage.error('获取购物车失败')
  } finally {
    loading.value = false
  }
}

// 更新商品数量
const updateQuantity = async (id, quantity) => {
  if (!checkLoginStatus()) return
  
  try {
    const res = await request.put('/cart/update/quantity', null, {
      params: { id, quantity }
    })
    if (res.code === 200) {
      // 更新本地数据
      const item = cartList.value.find(item => item.id === id)
      if (item) {
        item.quantity = quantity
      }
      ElMessage.success('更新成功')
    } else {
      ElMessage.error(res.message || '更新失败')
    }
  } catch (error) {
    console.error('更新数量失败:', error)
    ElMessage.error('更新失败')
  }
}

// 更新选中状态
const updateSelected = async (id, selected) => {
  if (!checkLoginStatus()) return
  
  try {
    const res = await request.put('/cart/update/selected', null, {
      params: { id, selected }
    })
    if (res.code === 200) {
      // 更新本地数据
      const item = cartList.value.find(item => item.id === id)
      if (item) {
        item.selected = selected
      }
    } else {
      ElMessage.error(res.message || '更新失败')
    }
  } catch (error) {
    console.error('更新选中状态失败:', error)
    ElMessage.error('更新失败')
  }
}

// 处理多选变化
const handleSelectionChange = (selection) => {
  // 根据多选框状态更新购物车选中状态
  cartList.value.forEach(item => {
    const isSelected = selection.some(selected => selected.id === item.id)
    if (item.selected !== isSelected) {
      updateSelected(item.id, isSelected)
    }
  })
}

// 更新全选状态
const updateAllSelected = async (selected) => {
  if (!checkLoginStatus()) return
  
  try {
    const res = await request.put('/cart/update/selected/batch', null, {
      params: { userId: userId.value, selected }
    })
    if (res.code === 200) {
      // 更新本地数据
      cartList.value.forEach(item => {
        item.selected = selected
      })
    } else {
      ElMessage.error(res.message || '更新失败')
    }
  } catch (error) {
    console.error('更新全选状态失败:', error)
    ElMessage.error('更新失败')
  }
}

// 删除购物车商品
const deleteCartItem = async (id) => {
  if (!checkLoginStatus()) return
  
  try {
    await ElMessageBox.confirm('确定要删除该商品吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await request.delete('/cart/delete', {
      params: { id }
    })
    if (res.code === 200) {
      // 更新本地数据
      cartList.value = cartList.value.filter(item => item.id !== id)
      ElMessage.success('删除成功')
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 清空购物车
const clearCart = async () => {
  if (!checkLoginStatus()) return
  
  try {
    await ElMessageBox.confirm('确定要清空购物车吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const res = await request.delete('/cart/clear', {
      params: { userId: userId.value }
    })
    if (res.code === 200) {
      cartList.value = []
      ElMessage.success('清空成功')
    } else {
      ElMessage.error(res.message || '清空失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清空失败:', error)
      ElMessage.error('清空失败')
    }
  }
}

// 结算
const checkout = () => {
  if (!checkLoginStatus()) return
  
  const selectedItems = cartList.value.filter(item => item.selected)
  if (selectedItems.length === 0) {
    ElMessage.warning('请选择要结算的商品')
    return
  }
  
  // 将选中的商品保存到本地存储，以便结算页面使用
  localStorage.setItem('checkoutItems', JSON.stringify(selectedItems))
  // 跳转到结算页面
  router.push('/checkout')
}

// 处理图片URL
const getImgUrl = (url) => {
  if (!url) return '';

  // 确保有服务器地址前缀
  let fullUrl = url;
  if (url.startsWith('/uploads/')) {
    fullUrl = SERVER_BASE_URL + url;
  }

  return fullUrl;
}

// 页面加载时获取购物车数据
onMounted(() => {
  getCartList()
})
</script>

<template>
  <div class="cart-container">
    <div class="cart-header">
      <h2>我的购物车</h2>
      <el-button type="danger" @click="clearCart" :disabled="cartList.length === 0">
        清空购物车
      </el-button>
    </div>

    <el-table
      v-loading="loading"
      :data="cartList"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      
      <el-table-column label="商品信息" min-width="400">
        <template #default="{ row }">
          <div class="commodity-info">
            <el-image
              :src="row.commodity.image && row.commodity.image.length > 0 ? getImgUrl(row.commodity.image[0]) : ''"
              :preview-src-list="(row.commodity.image).map(getImgUrl)"
              fit="cover"
              class="commodity-image"
              preview-teleported
            />
            <div class="commodity-detail">
              <h3>{{ row.commodity.name }}</h3>
              <div class="commodity-tags">
                <el-tag
                  v-for="tag in row.commodity.categoryTag"
                  :key="tag"
                  size="small"
                  class="tag"
                >
                  {{ tag }}
                </el-tag>
              </div>
            </div>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="单价" width="120">
        <template #default="{ row }">
          <span class="price">¥{{ row.commodity.price }}</span>
        </template>
      </el-table-column>

      <el-table-column label="数量" width="150">
        <template #default="{ row }">
          <el-input-number
            v-model="row.quantity"
            :min="1"
            :max="row.commodity.stock"
            size="small"
            @change="(value) => updateQuantity(row.id, value)"
          />
        </template>
      </el-table-column>

      <el-table-column label="小计" width="120">
        <template #default="{ row }">
          <span class="subtotal">¥{{ (row.quantity * row.commodity.price).toFixed(2) }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" width="100">
        <template #default="{ row }">
          <el-button
            type="danger"
            size="small"
            @click="deleteCartItem(row.id)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="cart-footer">
      <div class="left">
<!--        <el-checkbox-->
<!--          v-model="isAllSelected"-->
<!--          @change="updateAllSelected"-->
<!--        >-->
<!--          全选-->
<!--        </el-checkbox>-->
        <span class="selected-count">
          已选择 {{ selectedCount }} 件商品
        </span>
      </div>
      <div class="right">
        <div class="total-price">
          合计：<span class="price">¥{{ totalPrice.toFixed(2) }}</span>
        </div>
        <el-button
          type="primary"
          size="large"
          :disabled="selectedCount === 0"
          @click="checkout"
        >
          结算
        </el-button>
      </div>
    </div>
  </div>
</template>

<style scoped>
.cart-container {
  margin: 20px auto;
  width: 95%;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.cart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.cart-header h2 {
  margin: 0;
  font-size: 20px;
  color: #333;
}

.commodity-info {
  display: flex;
  align-items: center;
}

.commodity-image {
  width: 80px;
  height: 80px;
  margin-right: 15px;
  border-radius: 4px;
}

.commodity-detail {
  flex: 1;
}

.commodity-detail h3 {
  margin: 0 0 10px;
  font-size: 16px;
  color: #333;
}

.commodity-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.tag {
  margin-right: 5px;
}

.price {
  color: #f56c6c;
  font-weight: bold;
}

.subtotal {
  color: #f56c6c;
  font-weight: bold;
}

.cart-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
  padding: 20px 0;
  border-top: 1px solid #eee;
}

.left {
  display: flex;
  align-items: center;
}

.selected-count {
  margin-left: 20px;
  color: #666;
}

.right {
  display: flex;
  align-items: center;
}

.total-price {
  margin-right: 20px;
  font-size: 16px;
}

.total-price .price {
  font-size: 20px;
}
</style>